package edu.mju.ddc.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DBUtil {

	private static final String CLASS_NAME = "com.mysql.jdbc.Driver";
	
	private static final String URL = "jdbc:mysql://172.16.218.20:3306/bookshop";
	
	private static final String USER_NAME = "ddcuser";
	
	private static final String USER_PWD = "ddcpwd";
	
	private static DBUtil DBUTIL = new DBUtil();
	
	private DBUtil() {
		
	}
	
	public static DBUtil getInstance() {
		if (DBUTIL == null) {
			DBUTIL = new DBUtil();
		}
		return DBUTIL;
	}
	
	public Connection getConn() {
		
		Connection conn = null;
		
		try {
			Class.forName(CLASS_NAME);
			conn = DriverManager.getConnection(URL, USER_NAME, USER_PWD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return conn;
	}
	
	public Connection getConn(String className, String url, String username, String userPwd) {
		
		Connection conn = null;
		
		try {
			Class.forName(className);
			conn = DriverManager.getConnection(url, username, userPwd);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return conn;
	}
	
	
	
	public PreparedStatement getPstmt(String sql) {
		
		PreparedStatement pstmt = null;
		
		try {
			pstmt = getConn().prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (getConn() != null) {
					getConn().close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return pstmt;
	}
	
	public PreparedStatement getPstmt(Connection conn, String sql) {
		
		PreparedStatement pstmt = null;
		
		try {
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
	}
	
	
}
